package com.platform.usercenter.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.platform.common.core.domain.entity.ImUser;
import com.platform.common.core.domain.entity.SysUser;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.redis.service.RedisService;
import com.platform.constants.ImConstant;
import com.platform.constants.SysUserConstants;
import com.platform.usercenter.config.ConfigConstants;
import com.platform.usercenter.mapper.SysUserMapper;
import com.platform.usercenter.service.ImService;
import com.platform.usercenter.utils.HashCodeUtil;
import com.platform.usercenter.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ImServiceImpl implements ImService {
    @Resource
    RedisService  redisService;

    @Resource
    SysUserMapper userMapper;

    @Resource
    ConfigConstants configConstants;

    @Override
    public String getImTokenFromRedis(String flag) {
        String token=redisService.getCacheObject(ImConstant.IM_TOEKN_KEY);
        if(!StringUtils.isEmpty(token)&&StringUtils.isEmpty(flag)){
            return token;
        }
        JSONObject objtoken=new JSONObject();
        objtoken.put("grant_type",configConstants.getGrant_type());
        objtoken.put("client_id",configConstants.getClient_id());
        objtoken.put("client_secret",configConstants.getClient_secret());
        objtoken.put("ttl",configConstants.getTtl()+30);
        String imTokenUrl=configConstants.getImUlr()+ ImConstant.imTokenUrl;
        String res=HttpClientUtil.pushPost(imTokenUrl,objtoken.toJSONString(),null);
        log.info("获取IMtoken结果：{}",res);
        JSONObject tokenobj=JSONObject.parseObject(res);
        redisService.setCacheObject(ImConstant.IM_TOEKN_KEY,tokenobj.getString("access_token"),configConstants.getTtl(), TimeUnit.SECONDS);
        return tokenobj.getString("access_token");
    }

    @Override
    public void registerBatchUsers(Long[] userIds) throws Exception{
        String token=getImTokenFromRedis(null);
        if(StringUtils.isEmpty(token)){
            throw  new  Exception("获取token异常");
        }
        List<SysUser> list=userMapper.selectUserByIds(userIds);
        int pages=list.size()/60;
        int flag=list.size()%60;
        if(flag!=0){
            pages=pages+1;
        }
        for(int i=1;i<=pages;i++) {
            try {
                int endindex = 60 * i;
                if (endindex > list.size()) {
                    endindex = list.size();
                }
                List<SysUser> smlist = list.subList(60 * (i - 1), endindex);
                    JSONArray arr = new JSONArray();
                    for (SysUser su : smlist) {
                        JSONObject obj = new JSONObject();
                        obj.put("username", su.getUserName());
                        obj.put("nickname", su.getNickName());
                        obj.put("password", HashCodeUtil.getHashCode(su.getPassword()));
                        arr.add(obj);
                    }
                    String imUserUrl=configConstants.getImUlr()+ ImConstant.imUserUrl;
                    String res=HttpClientUtil.pushPost(imUserUrl,arr.toJSONString(),"Bearer "+token);
                    log.info("IM新增用户结果:{}",res);
                    JSONObject resobj=JSONObject.parseObject(res);
                    if(resobj.containsKey("error")){
                        log.error("IM新增用户{}异常：{}",arr.toJSONString(),res);
                        //throw  new  Exception(resobj.getString("error_description"));
                    }
                    /**更新用户属性*/
                    for(SysUser model:smlist){
                        try {
                            String userInfoUrl=configConstants.getImUlr()+ ImConstant.imUserInfo;
                            userInfoUrl=userInfoUrl.replace(ImConstant.IM_USER_NAME,model.getUserName());
                            Map<String, String> params=new HashMap<>();
                            params.put("nickname", model.getNickName());
                            params.put("avatarurl", model.getAvatar());
                            if("0".equals(model.getSex())){
                                params.put("gender", "1");
                            }else if("1".equals(model.getSex())){
                                params.put("gender", "2");
                            }else{
                                params.put("gender", "0");
                            }
                            log.info("设置用户{}信息：{}",model.getUserName(),params.toString());
                            JSONObject res_up=JSONObject.parseObject(HttpClientUtil.pushPutForm(userInfoUrl,params,"Bearer "+token));
                            log.info("IM设置用户{}信息结果:{}",model.getUserName(),res_up.toJSONString());
                        }catch (Exception e){
                            log.error("***更新用户-{}-IM设置用户信息失败：{}",model.getUserName(),e.getMessage());
                        }
                    }

            } catch (Exception e) {
                e.printStackTrace();
                log.error("*********IM用户批量注册异常：{}" + e.getMessage());
            }
        }
    }

    @Override
    public void updateImUserPwd(Long userId,String pwd) throws Exception{
        String token=getImTokenFromRedis(null);
        if(StringUtils.isEmpty(token)){
            log.error("****更新IM用户密码失败，原因：未获取到token");
            throw  new Exception("更新IM用户密码失败，原因：未获取到token");
        }
        SysUser model=userMapper.selectUserPwd(userId);
        if(model==null){
            log.error("****更新IM用户密码失败,原因未查询到用户,用户id：{}",userId);
            throw  new Exception("更新IM用户密码失败,原因未查询到用户");
        }
        String upPwdUrl=configConstants.getImUlr()+ ImConstant.imUpdatePwd;
        upPwdUrl=upPwdUrl.replace(ImConstant.IM_USER_NAME,model.getUserName());
        JSONObject obj=new JSONObject();
        obj.put("newpassword", HashCodeUtil.getHashCode(model.getPassword()));
        JSONObject res=JSONObject.parseObject(HttpClientUtil.pushPut(upPwdUrl,obj.toJSONString(),"Bearer "+token));
        log.info("修改用户{},IM修改密码结果:{}",model.getUserName(),res.toJSONString());
        if(res.containsKey("error")&&configConstants.isImSwitch()){
            //***用户不存在，则直接注册
            JSONArray arr=new JSONArray();
            JSONObject register=new JSONObject();
            register.put("username",model.getUserName());
            register.put("nickname",model.getNickName());
            register.put("password",HashCodeUtil.getHashCode(model.getPassword()));
            arr.add(register);
            String imUserUrl=configConstants.getImUlr()+ ImConstant.imUserUrl;
            HttpClientUtil.pushPost(imUserUrl,arr.toJSONString(),"Bearer "+token);
        }
    }


    @Override
    public void updateImUserPwdByUserName(String userName) throws Exception{
        String token=getImTokenFromRedis(null);
        if(StringUtils.isEmpty(token)){
            log.error("****更新IM用户密码失败，原因：未获取到token");
            throw  new Exception("更新IM用户密码失败，原因：未获取到token");
        }
        ImUser model=userMapper.selectSysUserPwdByUserName(userName);
        if(model==null){
            log.error("****更新IM用户密码失败,原因未查询到用户,用户id：{}",userName);
            throw  new Exception("更新IM用户密码失败,原因未查询到用户");
        }
        String upPwdUrl=configConstants.getImUlr()+ ImConstant.imUpdatePwd;
        upPwdUrl=upPwdUrl.replace(ImConstant.IM_USER_NAME,model.getUserName());
        JSONObject obj=new JSONObject();
        obj.put("newpassword",model.getPwd().hashCode());
        log.info("修改userName密码为：{}",model.getPwd().hashCode());
        JSONObject res=JSONObject.parseObject(HttpClientUtil.pushPut(upPwdUrl,obj.toJSONString(),"Bearer "+token));
        log.info("IM修改密码结果:{}",res.toJSONString());
        if(res.containsKey("error")){
            //***用户不存在，则直接注册
            JSONArray arr=new JSONArray();
            JSONObject register=new JSONObject();
            register.put("username",model.getUserName());
            register.put("nickname",model.getNickName());
            register.put("password",HashCodeUtil.getHashCode(model.getPwd()));
            arr.add(register);
            String imUserUrl=configConstants.getImUlr()+ ImConstant.imUserUrl;
            HttpClientUtil.pushPost(imUserUrl,arr.toJSONString(),"Bearer "+token);
        }
    }

    @Override
    public void updateImUserInfo(String userName) throws Exception {
        String token=getImTokenFromRedis(null);
        if(StringUtils.isEmpty(token)){
            log.error("****更新IM用户信息失败，原因：未获取到token");
            throw  new Exception("更新IM用户信息失败，原因：未获取到token");
        }
        ImUser imUser=new ImUser();
        imUser.setUserName(userName);
        List<SysUser> list=userMapper.selectAllSysUserPwd(imUser);
        for(SysUser model:list){
            try {
                String userInfoUrl=configConstants.getImUlr()+ ImConstant.imUserInfo;
                userInfoUrl=userInfoUrl.replace(ImConstant.IM_USER_NAME,model.getUserName());
                Map<String, String> params=new HashMap<>();
                params.put("nickname", model.getNickName());
                params.put("avatarurl", model.getAvatar());
                if("0".equals(model.getSex())){
                    params.put("gender", "1");
                }else if("1".equals(model.getSex())){
                    params.put("gender", "2");
                }else{
                    params.put("gender", "0");
                }
                log.info("设置用户{}信息：{}",model.getUserName(),params.toString());
                JSONObject res=JSONObject.parseObject(HttpClientUtil.pushPutForm(userInfoUrl,params,"Bearer "+token));
                log.info("IM设置用户{}信息结果:{}",model.getUserName(),res.toJSONString());
            }catch (Exception e){
                log.error("***更新用户-{}-IM设置用户信息失败：{}",model.getUserName(),e.getMessage());
            }
        }
    }

    @Override
    public void updateAllUserToIm() throws Exception {
        String token=getImTokenFromRedis("1");
        if(StringUtils.isEmpty(token)){
            throw  new  Exception("获取token异常");
        }
        List<SysUser> list=userMapper.selectAllSysUserPwd(null);
        for(SysUser model:list){
            try {
                String upPwdUrl=configConstants.getImUlr()+ ImConstant.imUpdatePwd;
                upPwdUrl=upPwdUrl.replace(ImConstant.IM_USER_NAME,model.getUserName());
                JSONObject obj=new JSONObject();
                obj.put("newpassword", HashCodeUtil.getHashCode(model.getPassword()));
                JSONObject res=JSONObject.parseObject(HttpClientUtil.pushPut(upPwdUrl,obj.toJSONString(),"Bearer "+token));
                log.info("修改用户{},IM修改密码结果:{}",model.getUserName(),res.toJSONString());
            }catch (Exception e){
                log.error("***更新用户-{}-IM密码失败：{}",model.getUserName(),e.getMessage());
            }
        }

    }

    @Async
    @Override
    public void registerAllUserToIm() throws Exception{
        String token=getImTokenFromRedis(null);
        if(StringUtils.isEmpty(token)){
            throw  new  Exception("获取token异常");
        }
        List<SysUser> list=userMapper.selectAllSysUserPwd(null);
        int pages=list.size()/60;
        int flag=list.size()%60;
        if(flag!=0){
            pages=pages+1;
        }
        for(int i=1;i<=pages;i++){
            try {
                int endindex=60*i;
                if(endindex>list.size()){
                    endindex=list.size();
                }
                List<SysUser> smlist=list.subList(60*(i-1),endindex);
                JSONArray arr=new JSONArray();
                for(SysUser su:smlist){
                    if(!StringUtils.isEmpty(su.getPassword())){
                        JSONObject obj=new JSONObject();
                        obj.put("username",su.getUserName());
                        obj.put("nickname",su.getNickName());
                        obj.put("password",HashCodeUtil.getHashCode(su.getPassword()));
                        arr.add(obj);
                    }
                }
                log.info("待注册的用户：{}",arr.toJSONString());
                String ImUserUrl=configConstants.getImUlr()+ ImConstant.imUserUrl;
                String res=HttpClientUtil.pushPost(ImUserUrl,arr.toJSONString(),"Bearer "+token);
                log.info("IM新增用户结果:{}",res);
            }catch (Exception e){
                e.printStackTrace();
                log.error("*********IM用户批量注册异常：{}"+e.getMessage());
            }
        }
    }

    @Override
    public void  deleteImUser() throws Exception{
        String token=getImTokenFromRedis(null);
        if(StringUtils.isEmpty(token)){
            throw  new  Exception("获取token异常");
        }
        List<SysUser> list=userMapper.selectDeleteSysUser();
        for(SysUser model:list){
            String deleteUrl=configConstants.getImUlr()+ ImConstant.imUserDelete;
            deleteUrl=deleteUrl.replace(ImConstant.IM_USER_NAME,model.getUserName());
            String res=HttpClientUtil.pushDelete(deleteUrl,"Bearer "+token);
            log.info("删除IM用户{}结果:{}",model.getUserName(),res);
        }
    }

    @Override
    public void  deleteBatchImUser(Long[] userIds) throws Exception{
        String token=getImTokenFromRedis(null);
        if(StringUtils.isEmpty(token)){
            throw  new  Exception("获取token异常");
        }
        List<SysUser> list=userMapper.selectUserInfoByUserIds(userIds);
        for(SysUser model:list){
            if(!StringUtils.isEmpty(model.getUserName())){
                String deleteUrl=configConstants.getImUlr()+ ImConstant.imUserDelete;
                deleteUrl=deleteUrl.replace(ImConstant.IM_USER_NAME,model.getUserName());
                String res=HttpClientUtil.pushDelete(deleteUrl,"Bearer "+token);
                log.info("删除IM用户{}结果:{}",model.getUserName(),res);
            }
        }
    }

    @Override
    public void updateBatchUsers(Long[] userIds) throws Exception {
        String token=getImTokenFromRedis(null);
        if(StringUtils.isEmpty(token)){
            log.error("****更新IM用户密码失败，原因：未获取到token");
            throw  new Exception("更新IM用户密码失败，原因：未获取到token");
        }
        List<SysUser> list=userMapper.selectUserByIds(userIds);
        for(SysUser model:list){
            try {
                /***修改密码**/
                String upPwdUrl=configConstants.getImUlr()+ ImConstant.imUpdatePwd;
                upPwdUrl=upPwdUrl.replace(ImConstant.IM_USER_NAME,model.getUserName());
                JSONObject obj=new JSONObject();
                obj.put("newpassword", HashCodeUtil.getHashCode(model.getPassword()));
                JSONObject res=JSONObject.parseObject(HttpClientUtil.pushPut(upPwdUrl,obj.toJSONString(),"Bearer "+token));
                log.info("修改用户{},IM修改密码结果:{}",model.getUserName(),res.toJSONString());
                if(res.containsKey("error")){
                    throw  new Exception("修改密码出错："+res.getString("error_description"));
                }
            }catch (Exception e){
                log.error("***更新用户-{}-IM密码失败：{}",model.getUserName(),e.getMessage());
                throw  new Exception("修改Im密码异常:"+e.getMessage());
            }

            /**修改Im属性：昵称*/
            try {
                String userInfoUrl=configConstants.getImUlr()+ ImConstant.imUserInfo;
                userInfoUrl=userInfoUrl.replace(ImConstant.IM_USER_NAME,model.getUserName());
                Map<String, String> params=new HashMap<>();
                params.put("nickname", model.getNickName());
                params.put("avatarurl", model.getAvatar());
                if("0".equals(model.getSex())){
                    params.put("gender", "1");
                }else if("1".equals(model.getSex())){
                    params.put("gender", "2");
                }else{
                    params.put("gender", "0");
                }
                log.info("设置用户{}信息：{}",model.getUserName(),params.toString());
                JSONObject res=JSONObject.parseObject(HttpClientUtil.pushPutForm(userInfoUrl,params,"Bearer "+token));
                log.info("IM设置用户{}信息结果:{}",model.getUserName(),res.toJSONString());
                if(res.containsKey("error")){
                    throw  new Exception("修改Im用户详情出错："+res.getString("error_description"));
                }
            }catch (Exception e){
                log.error("***更新用户-{}-IM设置用户信息失败：{}",model.getUserName(),e.getMessage());
                throw  new Exception("修改Im用户详情异常:"+e.getMessage());
            }
        }
    }
}
